
package com.hulk.dryad.manage.framework.lock.executor;

import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.boot.convert.DurationStyle;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;


/**
 * 分布式锁原生Redisson处理器
 * @author hulk
 */
@Slf4j
public class RedissonLockdExecutor implements LockdExecutor {

    RedissonClient redissonClient;

    public RedissonLockdExecutor(@NonNull RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @SneakyThrows
    @Override
    public boolean acquireLock(String key, String acquireTimeout, String expireTime) {
		Duration acquire = DurationStyle.detectAndParse(acquireTimeout, ChronoUnit.MILLIS);
		Duration expire = DurationStyle.detectAndParse(expireTime, ChronoUnit.MILLIS);
        return redissonClient.getLock(key).tryLock(acquire.toMillis(), expire.toMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public void releaseLock(String key) {
		RLock rLock = redissonClient.getLock(key);
		if (rLock.isHeldByCurrentThread()) {
			rLock.unlockAsync();
		}
    }

}